using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using System.Net.Sockets;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Security.Cryptography;
using System.Diagnostics;
using pop3dll;
using encryptit;
using SMTPdll;

namespace pop3
{
    public partial class msgViewer : Form
    {

        public int msgNum = 0;
        public ListView mListView;
        public Pop3Client j;
        int count;
        bool checkCount = true;
        public string replyAddress;
        public msgViewer()
        {
            InitializeComponent();
            

        }

        private void closeme_Tick(object sender, EventArgs e)
        {
            if (pop3.Pop3.closemeNOW)
                this.Close();
            if (checkCount)
            {
                count = j.getCount();
                msgNumL.Text = msgNum.ToString();
                checkCount = false;
            }
        }

        private void prevB_Click(object sender, EventArgs e)
        {

            msgNum -= 1;
            if (msgNum < 1)
            {
                msgNum = count;
            }
            setText(msgNum);
        }

        private void nextB_Click(object sender, EventArgs e)
        {
            msgNum += 1;
            if (msgNum > count)
            {
                msgNum = 1;
            }
            setText(msgNum);
        }

        private void delB_Click(object sender, EventArgs e)
        {
            if (msgNum > 0 && msgNum <= count)
            {
                if (j.deleteMessage(msgNum))
                    //infoTB.AppendText("Message " + msgNum + " was deleted.");
                    MessageBox.Show("Message " + msgNum + " was deleted");
                else
                    //infoTB.AppendText("Message " + msgNum + " was NOT deleted.");
                    MessageBox.Show("Message " + msgNum + " was NOT deleted");
            }
        }

        public void setText(int num) 
        {
            fromTB.Text = mListView.Items[num - 1].SubItems[2].Text;
            subjectTB.Text = mListView.Items[num - 1].SubItems[3].Text;
            dateTB.Text = mListView.Items[num - 1].SubItems[1].Text;
            string[] entireMessage = splitMessage(j.getMessage(num));
            splitBody(entireMessage);
            //msgViewerTB.Text = "THIS IS NOT WORKING YET YOU TWO GITS!";
            //htmlView.DocumentText = msgViewerTB.Text;
            msgNumL.Text = num.ToString();
            msgNumL.Update();
        }
        private string[] splitMessage(string message)
        {
            int a = message.IndexOf("\r\n\r\n");
            string[] entireMessage = new string[2];
            entireMessage[0] = message.Substring(0, a);
            entireMessage[1] = message.Substring(a);
            //MessageBox.Show(entireMessage[0]);
            //MessageBox.Show(entireMessage[1]);
            return entireMessage;

        }
        private void splitBody(string[] entireMessage) 
        {
            string[] bodyParts;
            msgViewerTB.Text = "";
            htmlView.DocumentText = "";
            bool itReallyIs = isMultiPart(entireMessage[0]);

            if (itReallyIs)
            {
                int b = entireMessage[0].ToLower().IndexOf("boundary=");
                int o = entireMessage[0].IndexOf("\r\n", b);
                int x = (o - b);
                string boundry;
                if (o != -1)
                {
                    boundry = entireMessage[0].Substring(b, x);
                }
                else
                {
                    entireMessage[0] = entireMessage[0] + "\r\n";
                    x = (entireMessage[0].IndexOf("\r\n", b) - b);
                    boundry = entireMessage[0].Substring(b, x);
                }


                boundry = boundry.Substring(9);
                bool sure = boundry.StartsWith("\"");
                if (sure)
                {
                    boundry = boundry.Substring(1);
                }
                bool yerp = boundry.EndsWith("\"");
                if(yerp)
                {
                    boundry = boundry.Remove(boundry.Length - 1);
                }
                //MessageBox.Show("Boundary = " + boundry);
                string[] delimity = new string[] { boundry };
                bodyParts = entireMessage[1].Split(delimity,StringSplitOptions.RemoveEmptyEntries);
                for (int i = 0; i < bodyParts.Length-1; i++)
                {
                    int c = bodyParts[i].IndexOf("\r\n\r\n");
                    int u = bodyParts[i].IndexOf("--", c);
                    int zbob = bodyParts[i].LastIndexOf("--");
                    int d =  u - c;
                    if (d >= 0){
                        

                        string bodyPartHeader = bodyParts[i].Substring(0, c);
                        //MessageBox.Show(bodyPartHeader, "bodyPartHeader");
                        //MessageBox.Show(bodyParts[i], "bodyParts" + i.ToString());
                        string current;
                        if (u != -1)
                        {
                            current = bodyParts[i].Substring(c, d);

                        }
                        else
                        {
                            current = bodyParts[i];
                        }


                        //searchForm searcher = new searchForm(current);
                        //searcher.Show();
                        bool foundBase64 = false;
                        int a = bodyPartHeader.IndexOf("html");
                        if (bodyPartHeader.IndexOf("base64") >= 0) { foundBase64 = true; }
                        
                        if (a < 0)
                        {
                            if (foundBase64)
                            {
                                int valOfName = bodyPartHeader.ToLower().IndexOf("name=") + 6;
                                int lengthOfName = (bodyPartHeader.IndexOf("\"", valOfName) - valOfName);
                                string attachmentName = bodyPartHeader.Substring(valOfName, lengthOfName);

                                if (!File.Exists(attachmentName))
                                {



                                    DialogResult saveAttach = MessageBox.Show("Save Attached: "+attachmentName,"Save Email attachment?.", MessageBoxButtons.OKCancel);
                                    if (saveAttach.Equals(DialogResult.OK))
                                    {
                                        FileStream attachment = new FileStream(attachmentName, FileMode.CreateNew);
                                        BinaryWriter bw = new BinaryWriter(attachment);
                                        byte[] dataToWrite = Convert.FromBase64String(current);
                                        bw.Write(dataToWrite, 0, dataToWrite.Length);

                                        msgViewerTB.Text += "Saved file " + attachmentName + "\r\n";
                                        ListViewItem attachItem = this.attachView.Items.Add(attachmentName.ToString());
                                        attachItem.SubItems.Add(attachment.Length.ToString());
                                        attachView.Update();
                                        bw.Close();
                                        attachment.Close();
                                        FileInfo thsi = new FileInfo(attachmentName);
                                        
                                        htmlView.Navigate(thsi.FullName);
                                    
                                    }
                                    else {
                                        msgViewerTB.Text += "Attachment " + attachmentName + " not saved. \r\n";
                                    
                                    }
                                    
                                }
                                else {
                                    msgViewerTB.Text += attachmentName + " exists already did not create!\r\n";
                                    msgViewerTB.Text += " found base64 encoded part\r\n";
                                
                                }



                                //MessageBox.Show(bodyPartHeader.Substring(valOfName, lengthOfName));
                                //MessageBox.Show(bodyPartHeader, "bodyPartHeader");
                                
                            }
                            else 
                            {
                                msgViewerTB.Text += current;
                                
                            }
                        }
                        else
                        {
                            htmlView.Navigate("about:blank");
                            htmlView.DocumentText = current;
                        }
                    }
                    else
                        MessageBox.Show(bodyParts[i], "THIS A MULTIHEADER");
                

                }

            }
            else
            {
                
                htmlView.Navigate("about:blank");
                msgViewerTB.Text += entireMessage[1];
                htmlView.DocumentText = entireMessage[1];
                
            }
            msgViewerTB.Update();
            htmlView.Update();
                /*
                for (int i = 0; i < bodyParts.Length; i++)
                {

                    
                   

                    //MessageBox.Show(bodyParts[i], "bodyParts in adding to form" + i.ToString());

                   
                }
                */
            
        }

        private bool isMultiPart(string header) 
        {
            bool answer = false;
            if(!(header.ToLower().IndexOf("content-type: multi") < 0 ))
                 answer = true;
             return answer;
        }
      /*  private string[] parseMulti(string header,string message) 
        {
            string[] parts;

            


            return parts;
        }
        */

        
        private void repB_Click(object sender, EventArgs e)
        {
            string mountainTo = "";
            Regex.CacheSize = 0;
            Match m = Regex.Match(fromTB.Text, "<*(\\S*@\\S*)");
            
            string s = m.ToString();
            //MessageBox.Show(s);
            if (s.StartsWith("<"))
            {
                mountainTo = s.Substring(1, s.Length - 2);
            }
            else
            {
                mountainTo = s;
            }
            //MessageBox.Show(mountainTo);
            
            SMTPviewer sClient = new SMTPviewer(replyAddress,mountainTo,subjectTB.Text,msgViewerTB.Text);
            
            sClient.Show();
            
        }

        private void searchB_Click(object sender, EventArgs e)
        {
            searchForm s = new searchForm(msgViewerTB.Text);
            Thread searcher = new Thread(delegate() { s.ShowDialog(); });
            searcher.Start();
            
        }

        private void attachView_DoubleClick(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start(attachView.Items[attachView.SelectedIndices[0]].Text);
           // msgViewerTB.Text += attachView.Items[attachView.SelectedIndices[0]].Text +"\r\n";
        }


    }
}